package com.wu.util;

import com.wu.pojo.model.DateMonth;
import com.wu.pojo.model.DateYear;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-23 11:24
 */
@Component
public class ArticleDataUtil {

    /**
     * 获取处理完毕的时间和文章数量(倒序)
     *
     * @param dataList
     * @return
     */
    public List<DateYear> getArticleDataClassify(List<String> dataList) {
        //获取所有的年
        Set<String> yearsSet = new HashSet<>();
        for (int i = 0; i < dataList.size(); i++) {
            yearsSet.add(dataList.get(i).substring(0, 4));
        }

        List<DateYear> dataCounts = new ArrayList<>();

        //把年排序
        String[] yearsString = new String[yearsSet.size()];
        int g = 0;
        for (String s : yearsSet) {
            yearsString[g++] = s;
        }
        Arrays.parallelSort(yearsString, (o1, o2) -> {
            if (Integer.parseInt(o1) < Integer.parseInt(o2)) {
                return 1;
            } else {
                return -1;
            }
        });
        //初始化所有的年和月
        for (int i = 0; i < yearsString.length; i++) {
            DateYear dataYear = new DateYear();
            dataYear.setYear(yearsString[i]);
            dataYear.setCount(0);
            List<DateMonth> list = new ArrayList<>();

            for (int j = 12; j >= 1; j--) {
                DateMonth monthCount = new DateMonth();
                String s = String.valueOf(j);
                if (j < 10) {
                    s = "0" + s;
                }
                monthCount.setMonth(s);
                monthCount.setCount(0);
                list.add(monthCount);
            }
            dataYear.setDataMonths(list);
            dataCounts.add(dataYear);
        }
        //上面代码初始化完成
        int len = dataCounts.size() - 1;
        for (int i = 0; i < dataList.size(); i++) {
            String subYear = dataList.get(i).substring(0, 4);//年
            String subMonth = dataList.get(i).substring(5, 7);//月
            for (int j = 0; j <= len; j++) {
                DateYear year = dataCounts.get(j);
                if (subYear.equals(year.getYear())) {
                    int k = year.getCount();
                    year.setCount(++k);
                    DateMonth month = year.getDataMonths().get(12 - Integer.parseInt(subMonth));
                    int l = month.getCount();
                    month.setCount(++l);
                }
            }
        }
        //移除一个月中文章数为0的月份
        for (int i = 0; i < dataCounts.size(); i++) {
            List<DateMonth> months = dataCounts.get(i).getDataMonths();
            List<DateMonth> res = new ArrayList<>();
            for (int j = 0; j < months.size(); j++) {
                if (months.get(j).getCount() != 0) {
                    res.add(months.get(j));
                }
            }
            dataCounts.get(i).setDataMonths(res);
        }
        return dataCounts;
    }


}
